package Tree;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: Tree
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-10-29  20:40
 * @Description: TODO
 * @Version: 1.0
 */
public class 二叉搜索树删除节点450 {

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }
        if (root.val == key) {
            // 当为叶子节点时候
            if (root.left == null && root.right == null) {
                return null;
            }
            // 当左为空 右不为空
            if (root.left == null && root.right != null) {
                return root.right;
            }
            // 当左不为空 右为空
            if (root.left != null && root.right == null) {
                return root.left;
            }
            // 当左右都不为空
            else {
                // 找到右子树的最左边值
                TreeNode curr = root.right;
                while (curr.left != null) {
                    curr = curr.left;
                }
                // 已经到右子树的最左边的值
                curr.left = root.left;
                return root.right;
            }
        }
        if (key < root.val) {
            root.left = deleteNode(root.left, key);
        } else {
            root.right = deleteNode(root.right, key);
        }
        return root;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
